class NewsApp {
    constructor() {
        this.baseUrl = 'http://localhost:8080'; // 根据实际情况修改
        this.currentPage = 'home';
        this.searchDebounceTimer = null; // 防抖定时器
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadNewsList();
    }

    bindEvents() {
        // 导航按钮事件
        document.getElementById('homeBtn').addEventListener('click', () => this.showPage('home'));
        document.getElementById('searchBtn').addEventListener('click', () => this.showPage('search'));
        document.getElementById('publishBtn').addEventListener('click', () => this.showPage('publish'));

        // 刷新按钮
        document.getElementById('refreshBtn').addEventListener('click', () => this.loadNewsList());

        // 搜索功能 - 输入时自动搜索（带防抖）
        document.getElementById('searchKeyword').addEventListener('input', (e) => {
            this.debouncedSearch();
        });
        
        // 保留按钮点击和回车搜索
        document.getElementById('searchBtnMain').addEventListener('click', () => this.performSearch());
        document.getElementById('searchKeyword').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                // 回车时立即搜索，清除防抖定时器
                this.clearSearchDebounce();
                this.performSearch();
            }
        });

        // 表单提交
        document.getElementById('newsForm').addEventListener('submit', (e) => this.handleFormSubmit(e));

        // 模态框关闭
        document.querySelector('.close').addEventListener('click', () => this.closeModal());
        document.getElementById('newsModal').addEventListener('click', (e) => {
            if (e.target.id === 'newsModal') {
                this.closeModal();
            }
        });
    }

    showPage(pageName) {
        // 隐藏所有页面
        document.querySelectorAll('.page').forEach(page => {
            page.classList.remove('active');
        });

        // 移除所有导航按钮的激活状态
        document.querySelectorAll('.nav-btn').forEach(btn => {
            btn.classList.remove('active');
        });

        // 显示目标页面
        document.getElementById(pageName + 'Page').classList.add('active');

        // 激活对应导航按钮
        document.getElementById(pageName + 'Btn').classList.add('active');

        this.currentPage = pageName;

        // 根据页面加载相应内容
        switch (pageName) {
            case 'home':
                this.loadNewsList();
                break;
            case 'search':
                document.getElementById('searchKeyword').focus();
                break;
            case 'publish':
                this.clearForm();
                break;
        }
    }

    async loadNewsList() {
        try {
            const response = await fetch(`${this.baseUrl}/list`);
            if (!response.ok) {
                throw new Error('获取新闻列表失败');
            }
            const newsList = await response.json();
            this.renderNewsList(newsList);
        } catch (error) {
            console.error('Error:', error);
            this.showToast('获取新闻列表失败: ' + error.message, 'error');
        }
    }

    renderNewsList(newsList) {
        const container = document.getElementById('newsList');

        if (!newsList || newsList.length === 0) {
            container.innerHTML = '<p class="no-news">📭 暂无新闻内容<br><small>点击"发布"按钮来创建第一条新闻吧！</small></p>';
            return;
        }

        const newsHtml = newsList.map(news => `
            <div class="news-item">
                <h3>${this.escapeHtml(news.title)}</h3>
                <div class="news-meta">
                    ${news.category ? `<span>📂 ${this.escapeHtml(news.category)}</span>` : ''}
                    <span>👤 ${this.escapeHtml(news.author || '未知')}</span>
                    <span>📅 ${this.formatDate(news.createTime || new Date())}</span>
                </div>
                <div class="news-preview">
                    ${this.escapeHtml(this.getPreview(news.content || ''))}
                </div>
                <div class="news-actions">
                    <button class="btn btn-primary btn-small" onclick="app.showNewsDetail(${news.id})">📖 查看详情</button>
                    <button class="btn btn-warning btn-small" onclick="app.editNews(${news.id})">✏️ 编辑</button>
                    <button class="btn btn-danger btn-small" onclick="app.deleteNews(${news.id})">🗑️ 删除</button>
                </div>
            </div>
        `).join('');

        container.innerHTML = newsHtml;
    }

    // 防抖搜索
    debouncedSearch() {
        // 清除之前的定时器
        this.clearSearchDebounce();
        
        const keyword = document.getElementById('searchKeyword').value.trim();
        
        // 如果输入为空，清空搜索结果
        if (!keyword) {
            document.getElementById('searchResults').innerHTML = '';
            return;
        }
        
        // 设置新的定时器，500ms后执行搜索
        this.searchDebounceTimer = setTimeout(() => {
            this.performSearch();
        }, 500);
    }

    // 清除防抖定时器
    clearSearchDebounce() {
        if (this.searchDebounceTimer) {
            clearTimeout(this.searchDebounceTimer);
            this.searchDebounceTimer = null;
        }
    }

    async performSearch() {
        const keyword = document.getElementById('searchKeyword').value.trim();
        if (!keyword) {
            return; // 静默返回，不显示错误提示
        }

        try {
            const response = await fetch(`${this.baseUrl}/search?keyword=${encodeURIComponent(keyword)}`);
            if (!response.ok) {
                throw new Error('搜索失败');
            }
            const results = await response.json();
            this.renderSearchResults(results);
        } catch (error) {
            console.error('Error:', error);
            this.showToast('搜索失败: ' + error.message, 'error');
        }
    }

    renderSearchResults(results) {
        const container = document.getElementById('searchResults');

        if (!results || results.length === 0) {
            container.innerHTML = '<p class="no-results">🔍 未找到相关新闻<br><small>试试其他关键词吧！</small></p>';
            return;
        }

        const resultsHtml = results.map(result => {
            // 处理后端ES返回的带<em>标签的高亮内容 - 对所有四个字段都应用高亮
            const highlightedCategory = this.processESHighlight(result.category || '');
            const highlightedTitle = this.processESHighlight(result.title);
            const highlightedAuthor = this.processESHighlight(result.author || '未知');
            const highlightedPreview = this.processESHighlight(this.getPreview(result.content || ''));

            return `
            <div class="news-item">
                <h3>${highlightedTitle}</h3>
                <div class="news-meta">
                    ${result.category ? `<span>📂 ${highlightedCategory}</span>` : ''}
                    <span>👤 ${highlightedAuthor}</span>
                    <span>📅 ${this.formatDate(result.createTime || new Date())}</span>
                    <span>⭐ ${result.score || 'N/A'}</span>
                </div>
                <div class="news-preview">
                    ${highlightedPreview}
                </div>
                <div class="news-actions">
                    <button class="btn btn-primary btn-small" onclick="app.showNewsDetail(${result.id})">📖 查看详情</button>
                    <button class="btn btn-warning btn-small" onclick="app.editNews(${result.id})">✏️ 编辑</button>
                    <button class="btn btn-danger btn-small" onclick="app.deleteNews(${result.id})">🗑️ 删除</button>
                </div>
            </div>
        `;
        }).join('');

        container.innerHTML = resultsHtml;
    }

    processESHighlight(text) {
        if (!text) return '';
        
        // 提取<em>标签中的内容，用自定义样式高亮显示
        const parts = [];
        let lastIndex = 0;
        const regex = /<em>(.*?)<\/em>/g;
        let match;
        
        while ((match = regex.exec(text)) !== null) {
            // 添加<em>标签之前的普通文本（需要转义）
            if (match.index > lastIndex) {
                parts.push(this.escapeHtml(text.substring(lastIndex, match.index)));
            }
            // 提取em标签中的内容，用自定义样式包裹实现高亮效果
            parts.push(`<span style="color: #ff4444; font-weight: bold; background-color: #fff3cd;">${this.escapeHtml(match[1])}</span>`);
            lastIndex = regex.lastIndex;
        }
        
        // 添加最后剩余的普通文本（需要转义）
        if (lastIndex < text.length) {
            parts.push(this.escapeHtml(text.substring(lastIndex)));
        }
        
        return parts.join('');
    }

    highlightKeyword(text, keyword) {
        if (!keyword || !text) return text;
        const regex = new RegExp(`(${this.escapeRegExp(keyword)})`, 'gi');
        return text.replace(regex, '<em>$1</em>'); // 高亮关键词
    }

    escapeRegExp(string) {
        return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    async showNewsDetail(id) {
        try {
            const response = await fetch(`${this.baseUrl}/list`);
            if (!response.ok) {
                throw new Error('获取新闻详情失败');
            }
            const allNews = await response.json();
            const news = allNews.find(n => n.id === id);

            if (!news) {
                const detailResponse = await fetch(`${this.baseUrl}news/${id}`);
                if (detailResponse.ok) {
                    const detailNews = await detailResponse.json();
                    this.renderNewsDetail(detailNews);
                } else {
                    throw new Error('未找到该新闻');
                }
            } else {
                this.renderNewsDetail(news);
            }
        } catch (error) {
            console.error('Error:', error);
            this.showToast('获取新闻详情失败: ' + error.message, 'error');
        }
    }

    renderNewsDetail(news) {
        const modal = document.getElementById('newsModal');
        const content = document.getElementById('newsDetailContent');

        content.innerHTML = `
            <h2>${this.escapeHtml(news.title)}</h2>
            <div class="news-detail-meta">
                ${news.category ? `<p><strong>📂 分类:</strong> ${this.escapeHtml(news.category)}</p>` : ''}
                <p><strong>👤 作者:</strong> ${this.escapeHtml(news.author || '未知')}</p>
                <p><strong>📅 发布时间:</strong> ${this.formatDate(news.createTime || new Date())}</p>
                <p><strong>🔖 新闻ID:</strong> ${news.id}</p>
            </div>
            <div class="news-detail-content">
                ${this.escapeHtml(news.content || '').replace(/\n/g, '<br>')}
            </div>
        `;

        modal.style.display = 'block';
    }

    closeModal() {
        document.getElementById('newsModal').style.display = 'none';
    }

    async deleteNews(id) {
        // 确认删除
        if (!confirm('确定要删除这条新闻吗？此操作不可撤销！')) {
            return;
        }

        try {
            const response = await fetch(`${this.baseUrl}/news/${id}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                this.showToast('新闻删除成功！', 'success');
                // 刷新列表
                if (this.currentPage === 'home') {
                    this.loadNewsList();
                } else if (this.currentPage === 'search') {
                    this.performSearch();
                }
            } else {
                throw new Error('删除失败');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showToast('删除失败: ' + error.message, 'error');
        }
    }

    async editNews(id) {
        try {
            // 获取新闻详情
            const response = await fetch(`${this.baseUrl}/list`);
            if (!response.ok) {
                throw new Error('获取新闻详情失败');
            }
            const allNews = await response.json();
            const news = allNews.find(n => n.id === id);

            if (!news) {
                const detailResponse = await fetch(`${this.baseUrl}/news/${id}`);
                if (detailResponse.ok) {
                    const detailNews = await detailResponse.json();
                    this.fillEditForm(detailNews);
                } else {
                    throw new Error('未找到该新闻');
                }
            } else {
                this.fillEditForm(news);
            }
        } catch (error) {
            console.error('Error:', error);
            this.showToast('获取新闻详情失败: ' + error.message, 'error');
        }
    }

    fillEditForm(news) {
        // 切换到发布页面
        this.showPage('publish');
        
        // 填充表单
        document.getElementById('newsId').value = news.id;
        document.getElementById('newsTitle').value = news.title;
        document.getElementById('newsCategory').value = news.category || '';
        document.getElementById('newsAuthor').value = news.author;
        document.getElementById('newsContent').value = news.content;
        
        // 修改表单标题和按钮文字
        document.querySelector('#publishPage h2').textContent = '✏️ 编辑新闻';
        document.querySelector('#newsForm button[type="submit"]').textContent = '💾 更新新闻';
    }

    async handleFormSubmit(e) {
        e.preventDefault();

        const formData = new FormData(e.target);
        const newsId = formData.get('newsId');
        const newsData = {
            title: formData.get('title').trim(),
            category: formData.get('category').trim(),
            author: formData.get('author').trim(),
            content: formData.get('content').trim()
        };

        // 🔍 调试日志：查看前端发送的数据
        console.log('📤 前端准备发送的数据:', newsData);
        console.log('📋 表单所有字段:', {
            title: formData.get('title'),
            category: formData.get('category'),
            author: formData.get('author'),
            content: formData.get('content')
        });

        if (!newsData.title || !newsData.category || !newsData.author || !newsData.content) {
            this.showToast('请填写所有必填字段', 'error');
            return;
        }

        try {
            let response;
            
            // 判断是更新还是新增
            if (newsId) {
                // 更新新闻
                response = await fetch(`${this.baseUrl}/news/${newsId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(newsData)
                });
                
                if (response.ok) {
                    this.showToast('新闻更新成功！', 'success');
                    this.clearForm();
                    this.showPage('home');
                } else {
                    const errorText = await response.text();
                    throw new Error(errorText || '更新失败');
                }
            } else {
                // 新增新闻
                response = await fetch(`${this.baseUrl}/publish`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(newsData)
                });

                if (response.ok) {
                    this.showToast('新闻发布成功！', 'success');
                    this.clearForm();
                    this.showPage('home');
                } else {
                    const errorText = await response.text();
                    throw new Error(errorText || '发布失败');
                }
            }
        } catch (error) {
            console.error('Error:', error);
            this.showToast(newsId ? '更新失败: ' + error.message : '发布失败: ' + error.message, 'error');
        }
    }

    clearForm() {
        const form = document.getElementById('newsForm');
        form.reset();
        
        // 重置表单标题和按钮文字
        document.querySelector('#publishPage h2').textContent = '✍️ 发布新闻';
        document.querySelector('#newsForm button[type="submit"]').textContent = '✨ 发布新闻';
    }

    showToast(message, type = 'success') {
        const toast = document.getElementById('messageToast');
        const messageText = document.getElementById('messageText');

        messageText.textContent = message;
        toast.className = `toast ${type}`;
        toast.style.display = 'flex';

        setTimeout(() => {
            toast.style.display = 'none';
        }, 3000);
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    getPreview(content, length = 100) {
        if (!content) return '暂无内容';
        return content.length > length ? content.substring(0, length) + '...' : content;
    }

    formatDate(date) {
        if (!date) return new Date().toLocaleString();

        let dateObj;
        if (typeof date === 'string') {
            dateObj = new Date(date);
        } else if (typeof date === 'number') {
            dateObj = new Date(date);
        } else {
            dateObj = date;
        }

        if (isNaN(dateObj.getTime())) {
            return new Date().toLocaleString();
        }

        return dateObj.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }
}

// 初始化应用
const app = new NewsApp();

// 点击模态框外部关闭模态框
window.onclick = function(event) {
    const modal = document.getElementById('newsModal');
    if (event.target === modal) {
        app.closeModal();
    }
}